<!--
 * @Author: yl
 * @Date: 2024-04-09 16:07:23
 * @LastEditTime: 2024-06-06 14:27:32
 * @LastEditors: Please set LastEditors
 * @Description: 系统个体溯源页面
-->
<template>
  <BaseMainSlot :show-tab="false" :show-search-box="false">
    <template v-slot:btn-box>
      <ActionBar v-show="!showTraceInfo" :page-no="603" :add-active="addActive" :del-active="delActive"
        :edit-active="editActive" :has-edit="false" :has-save="false" @add="add" @edit="edit" @del="del" />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <div class="common-search-item">
          <div class="label"></div>
          <div class="input"></div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <ZnFilterTable v-if="tableUpStauts === 1 && !showTraceInfo" :loadings="loading" :list-data="tableData"
        :prop-list="tableDataList" scope-no="traceConfigNo"
        @handleSelectionChange="handleSelectionChange($event, 'traceConfigNo')" @tableUpdate="tableUpdate">
        <template v-slot:url="{ row }">
          <el-button class="text-btn-cursor" type="text" size="small" @click="previewImg(row)">点击查看</el-button>
        </template>
        <template v-slot:operation="{ row }">
          <el-button class="text-btn-cursor" type="text" size="small" @click="handleTraceInfor(row)">
            <i class="el-icon-edit-outline"></i> 查看溯源信息
          </el-button>
          <el-button v-if="judgePermission(603, 'edit')" class="text-btn-cursor" type="text" size="small"
            @click="edit(row)">
            <i class="el-icon-edit-outline"></i> 修改
          </el-button>
          <el-button v-else-if="!judgePermission(603, 'edit')" class="text-btn-cursor" type="text" size="small"
            disabled>
            <i class="el-icon-edit-outline"></i> 修改
          </el-button>
          <el-button v-if="judgePermission(603, 'delete')" class="text-btn-cursor cursor-delete" type="text"
            size="small" @click="handleDelete(row.traceConfigNo)">
            <i class="el-icon-delete"></i> 删除
          </el-button>
          <el-button v-else-if="!judgePermission(603, 'delete')" class="text-btn-cursor cursor-delete" type="text"
            size="small" disabled>
            <i class="el-icon-delete"></i> 删除
          </el-button>
        </template>
      </znfiltertable>
      <Pagination v-show="!showTraceInfo" :page-size="pageSize" :current-page="currentPage" :total-size="totalSize"
        @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />

      <!-- <TraceInformation v-show="showTraceInfo" /> -->
      <TraceInformation v-if="showTraceInfo" ref="traceInfo" @back="TraceInforClose" />

    </template>
    <template v-slot:dialog>
      <el-dialog :title="titleText + '溯源信息'" :visible.sync="dialogFormVisible" @close="cancel('formData')">
        <el-form ref="formData" label-position="left" :model="formData" :rules="rules" class="el-form">
          <el-form-item v-for="item, index in formDataList" :key="index" :label="item.name + ':'" :prop="item.porp"
            class="w100p">
            <el-input v-if="item.type === 'input' && item.inputType !== 'number'" v-model="formData[`${item.porp}`]"
              :placeholder="'请输入' + item.name" :disabled="nowChanceStau === 'edit' && item.porp == 'fishVarietyName'"
              clearable />
            <el-input-number v-if="item.type === 'input' && item.inputType === 'number'"
              v-model.number="formData[`${item.porp}`]" :type="item.inputType" :placeholder="'请输入' + item.name"
              clearable controls-position="right" :min="0" />
            <el-select v-if="item.type === 'Select' && item.linkage === 'batchInfo'" :ref="item.linkage"
              v-model="formData[`${item.porp}`]" :placeholder="'请选择' + item.name" clearable :multiple="item.multiple"
              collapse-tags :disabled="nowChanceStau === 'edit'" :value-key="item.linkage"
              @change="SelectLinkage($event, item.linkage, item.typeObj.list, index - 1, item)">
              <el-option v-for="items, indexs in item.typeObj.list" :key="indexs"
                :label="items[item.typeObj.listName[0]]" :value="items[item.typeObj.listName[1]]" />
            </el-select>
            <el-select v-if="item.type === 'Select' && item.linkage !== 'batchInfo'" v-model="formData[`${item.porp}`]"
              filterable :placeholder="'请选择' + item.name" clearable
              @change="SelectLinkage($event, item.linkage, item.typeObj.list, index - 1, item)">
              <el-option v-for="items, indexs in item.typeObj.list" :key="indexs"
                :label="items[item.typeObj.listName[0]]" :value="items[item.typeObj.listName[1]]" />
            </el-select>
            <el-date-picker v-if="item.type === 'TimePicker'" v-model="formData[`${item.porp}`]" type="date"
              value-format="yyyy-MM-dd" :placeholder="'选择' + item.name" />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import SearchBox from "@/components/SearchBox";
import { mymixin } from "@/utils/mixins";
import { formatTime } from '@/utils/zhechart.js';
import TraceInformation from "@/views/trace-source-web/components/traceability-information/index.vue";

import traceConfigApi from "@/api/trace-source-web/traceConfig";
// 生产单位信息
import manufacturerApi from "@/api/trace-source-web/base-infor-manage/manufacturer-management";
// 产品信息
import productApi from "@/api/trace-source-web/base-infor-manage/product-infor-management";
// 主体信息
import proprietorrApi from "@/api/trace-source-web/base-infor-manage/proprietorr-management";
// 批次信息
import sheepApi from "@/api/basic-info-manage/sheep-management/sheep-information";
//养殖品种
import breedVarietiesApi from "@/api/trace-source-web/base-infor-manage/breed-varieties-management.js";
import sheepInformation from "@/api/basic-info-manage/sheep-management/sheep-information";
export default {
  name: "BatchTraceabilityInformationManage",
  components: {
    ActionBar,
    SearchBox,
    TraceInformation
  },
  mixins: [mymixin],
  data() {
    return {
      showTraceInfo: false,
      sheepSelectDialog: false,
      selectType: "single",
      initialParameters: {},
      breedTypeName: "",
      isClosePond: true,
      // 员工姓名
      breedTypeNo: "",
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      delList: [],
      formData: {
        person: {}
      },
      tableDataList: [
        {
          type: "Select", // input Select Checkbox TimePicker
          porps: 'batchInfo',
          porp: "batchName",
          porpName: "batchName",
          typeObj: {},
          name: "批次名称",
          required: true
        },

        {
          type: "Select", // input Select Checkbox TimePicker
          porps: 'batchInfo',
          porp: "batchNo",
          linkage: 'batchNo',
          typeObj: {},
          name: "批次编号",
          required: true
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          porps: "manufacturer",
          porp: "manufacturerNo",
          porpName: "manufacturerName",
          typeObj: {},
          name: "生产单位",
          notSearch: true,
          required: false
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          porps: "proprietor",
          porp: "proprietorNo",
          porpName: "proprietorName",
          typeObj: {},
          notSearch: true,
          name: "主体名称",
          required: false
        },
        {
          type: "date", // input Select Checkbox TimePicker
          porp: "generationDate",
          porpName: "generationDate",
          typeObj: {},
          name: "生成日期",
          required: false
        },
        {
          porp: 'operation', name: '操作', slotName: 'operation', fixed: true,
          minWidth: "160",
          typeObj: {},
          show: false,
          notSearch: true
        }
      ],
      formDataList: [
        {
          type: "Select", // input Select Checkbox TimePicker
          porp: "batchNo",
          linkage: 'batchInfo',
          typeObj: {},
          name: "批次名称",
          required: true
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          porp: "proprietorNo",
          linkage: 'proprietor',
          typeObj: {},
          name: "主体名称",
          required: true
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          porp: "productNo",
          linkage: 'product',
          typeObj: {},
          name: "关联产品",
          required: true
          // rules:
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          porp: "manufacturerNo",
          linkage: 'manufacturer',
          typeObj: {},
          name: "生产单位",
          required: false
        },
        {
          type: "TimePicker", // input Select Checkbox TimePicker
          porp: "factoryDate",
          typeObj: {},
          name: "出厂日期",
          required: false
        }
      ],
      rules: {
        batchNo: [
          {
            required: true,
            message: "批次不能为空",
            trigger: ["blur", "change"]
          }
        ],
        proprietorNo: [
          {
            required: true,
            message: "主体名称不能为空",
            trigger: ["blur", "change"]
          }
        ],
        productNo: [
          {
            required: true,
            message: "关联产品不能为空",
            trigger: ["blur", "change"]
          }
        ],
        manufacturerNo: [
          {
            required: true,
            message: "生产单位不能为空",
            trigger: ["blur", "change"]
          }
        ],
        factoryDate: [
          {
            required: true,
            message: "出厂日期不能为空",
            trigger: ["blur", "change"]
          }
        ]
      },
      topitemtypestu: true,
      searchObj: {},
      // 图片
      imgObj: {},
      uploadPictureList: [],
      breedVarietyData: [],
      dialogImgVisible: false
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    // 查询部门
    // 获取表格数据
    this.search();
    this.filterFishFormDataList();
    this.queryPlantVariety();
  },
  methods: {
    filterFishFormDataList() {
      let addEditFlag = this.nowChanceStau;
      if (sessionStorage.farmingTypeNo !== 'sc') return;
      this.formDataList = this.formDataList.filter(item => {
        return item.porp !== 'fishVarietyId' && item.porp !== 'fishVarietyName'
      })
      if (addEditFlag !== 'edit') {
        this.formDataList.splice(1, 0, {
          type: "Select",
          porp: "fishVarietyId",
          linkage: 'batchInfo',
          typeObj: {},
          name: "批次品种",
          required: true
        })
      } else {
        this.formDataList.splice(1, 0, {
          type: "input",
          porp: "fishVarietyName",
          linkage: 'batchInfo',
          typeObj: {},
          name: "批次品种",
          required: true
        })
      }
    },
    handleTraceInfor(row) {
      // console.log(row);
      this.showTraceInfo = true;
      this.$nextTick(() => {
        this.$refs.traceInfo.queryTraceInfo(row, 603);
      })
    },
    TraceInforClose(refresh) {
      if (refresh) {
        this.search();
      }
      this.showTraceInfo = false;
    },
    async getList() {
      // 条件查询生产单位
      manufacturerApi.getByCondition({}).then(res => {
        this.listfor({
          formDataList: ["formDataList", 'tableDataList'],
          porp: "manufacturerNo",
          list: res.data,
          listName: ["manufacturerName", "manufacturerNo"]
        });
      })
      // 条件查询产品
      productApi.getByCondition({}).then(res => {
        this.listfor({
          formDataList: ["formDataList", 'tableDataList'],
          porp: "productNo",
          list: res.data,
          listName: ["productName", "productNo"]
        });
      })
      // 条件查询主体
      proprietorrApi.getByCondition({}).then(res => {
        this.listfor({
          formDataList: ["formDataList", 'tableDataList'],
          porp: "proprietorNo",
          list: res.data,
          listName: ["proprietorName", "proprietorNo"]
        });
      })
      if (sessionStorage.farmingTypeNo === 'xm') {
        // batchStatus: "FINISHED"
        sheepApi.queryfattenBatch({}).then(res => {
          this.listfor({
            formDataList: 'formDataList',
            porp: "batchNo",
            list: res.data.content,
            listName: ["batchName", "fattenBatchNo"]
          });
          this.listfor({
            formDataList: 'tableDataList',
            porp: "batchNo",
            list: res.data.content,
            listName: ["fattenBatchNo", "fattenBatchNo"]
          });
          this.listfor({
            formDataList: 'tableDataList',
            porp: "batchName",
            list: res.data.content,
            listName: ["batchName", "batchName"]
          });
        })
      } else if (sessionStorage.farmingTypeNo === 'sc') {
        //水产
        sheepApi.queryFishBatch({ batchType: "BREEDING" }).then(res => {
          console.log('水产', res.data)
          this.listfor({
            formDataList: ["formDataList"],
            porp: "batchNo",
            list: res.data || [],
            listName: ["batchName", "batchCode"]
          });
          this.listfor({
            formDataList: ['tableDataList'],
            porp: "batchNo",
            list: res.data || [],
            listName: ["batchNo", "batchCode"]
          });
          this.listfor({
            formDataList: ["formDataList", 'tableDataList'],
            porp: "batchName",
            list: res.data || [],
            listName: ["batchName", "batchName"]
          });
        })
      } else if (['dt', 'dp'].includes(sessionStorage.farmingTypeNo)) {
        sheepApi.queryPlateBatch({
          "farmingTypeNo": "dt",
          "batchType": "BATCH",
          "simpleData": true,
          "systemNo": "MN",
          "status": 1
        }).then(res => {
          this.listfor({
            formDataList: ["formDataList"],
            porp: "batchNo",
            list: res.data,
            listName: ["batchName", "batchNo"]
          });
          this.listfor({
            formDataList: ['tableDataList'],
            porp: "batchNo",
            list: res.data,
            listName: ["batchNo", "batchNo"]
          });
          this.listfor({
            formDataList: ["formDataList", 'tableDataList'],
            porp: "batchName",
            list: res.data,
            listName: ["batchName", "batchName"]
          });
        })
      }
    },
    async SelectLinkage(e, linkage, list, x, item) {
      if (x && linkage !== 'batchInfo') {
        let index = list.findIndex(item => item[linkage + 'No'] === e)
        if (index !== -1) {
          this.$set(this.formData, linkage, list[index]);
        }
      } else {
        let index = list.findIndex(item => item['fattenBatchNo'] === e)
        if (index !== -1) {
          console.log(this.formData, list[index], list)
          this.$set(this.formData, linkage, { ...list[index], buildingNo: list[index] && list[index].batchHouseList[0].buildingNo, batchNo: list[index].fattenBatchNo, breedVarietyNo: list[index].plantVarietyNo });
        }
      }

      if (item.porp == 'batchNo' && sessionStorage.farmingTypeNo === 'sc') {
        let rut = list.filter(i => {
          return i.batchCode == e
        })
        this.queryFacility(rut[0] ? rut[0].facilityId : '')
        if (!rut[0].closePondDate) {
          this.isClosePond = false;
          this.$message.warning('该批次未封塘,请封塘后添加溯源码!')
        } else {
          this.isClosePond = true;
        }
        this.$set(this.formData, 'startTime', rut[0] && rut[0].closePondDate ? formatTime(rut[0].closePondDate, 'yyyy-MM-dd') : '');
        this.$set(this.formData, 'endTime', rut[0] && rut[0].completeDate ? formatTime(rut[0].completeDate, 'yyyy-MM-dd') : '');
        this.$set(this.formData, 'batchName', rut[0] ? rut[0].batchName : '');
        this.$set(this.formData, 'fishVarietyId', '');
        this.$set(this.formData, 'fishVarietyName', '');
        sheepApi.queryFishBatchPond(e).then(res => {
          this.listfor({
            formDataList: ["formDataList"],
            porp: "fishVarietyId",
            list: res.data,
            listName: ["plantVarietyName", "plantVarietyId"]
          });
        })
      }
      if (item.porp == "fishVarietyId" && sessionStorage.farmingTypeNo === 'sc') {
        let rut = this.breedVarietyData.find(item => {
          console.log(item.fishVarietyId, e, item.fishVarietyName)
          return item.fishVarietyId == e
        })
        this.$set(this.formData, 'fishVarietyId', rut.fishVarietyId);
        this.$set(this.formData, 'fishVarietyName', rut.fishVarietyName);
        this.$set(this.formData, 'breedVarietyPictureNo', rut.breedVarietyPictureNo);
      }
      if (item.porp == "batchNo" && ['dt', 'dp'].includes(sessionStorage.farmingTypeNo)) {
        sheepApi.queryPlateBatchByNo({
          no: this.formData.batchNo
        }).then(res => {
          this.$set(this.formData, 'facilityNos', res.data.facilityNos)
          let index = list.findIndex(item => item['batchNo'] === e)
          if (index !== -1) {
            this.$set(this.formData, linkage, { ...list[index], startTime: res.data.assetDate });
          }
        })
      }
    },
    queryPlantVariety() {
      if (sessionStorage.farmingTypeNo == 'sc') {
        breedVarietiesApi.queryPlantVariety({}).then((res) => {
          console.log(res.data)
          this.breedVarietyData = res.data.map(el => {
            return {
              fishVarietyName: el.plantVarietyName,
              fishVarietyId: el.plantVarietyId,
              breedVarietyPictureNo: el.pictureNo
            }
          })
        });
      }
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          ...this.searchObj,
          "traceType": "批次",
          "sourceType": "系统生成"
        }
      };
      traceConfigApi.pageQuery(params).then((res) => {
        this.loading = false;
        let data = res.data;
        // 赋值总条数
        if (data) {
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = JSON.parse(
            this.livestock(JSON.stringify(data.content))
          );
          // console.log(this.tableData)
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list, No) {
      this.delList = [];
      this.delList = list.map((item) => item[No]);
      if (this.delList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      traceConfigApi.numberBatchDel({ noList: this.delList }).then((res) => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.search();
        } else {
          this.$message.warning(res.msg || "删除失败");
        }
      });
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          traceConfigApi.numberDel(val).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除"
          // });
        });
    },
    addPlus() {
      this.uploadPictureList = [];
      this.$set(this.formData, "breedTypeNo", sessionStorage.breedTypeNo);
    },
    editPlus(row) {
      this.formData = { ...row }
      this.$set(this.formData, 'batchNo', row.batchInfo.batchNo)
      this.$set(this.formData, 'fishVarietyId', row.batchInfo.fishVarietyId)
      this.$set(this.formData, 'fishVarietyName', row.batchInfo.fishVarietyName)
      sheepApi.queryFishBatchPond(row.batchInfo.batchNo).then(res => {
        this.listfor({
          formDataList: ["formDataList"],
          porp: "fishVarietyId",
          list: res.data,
          listName: ["plantVarietyName", "plantVarietyId"]
        });
      })
      this.filterFishFormDataList();
      // this.listfor({
      //   formDataList: "formDataList",
      //   porp: "batchNo",
      //   list: [row.batchInfo],
      //   listName: ["batchName", "batchNo"]
      // });
      // console.log(this.formData);
    },
    queryFacility(id) {
      sheepInformation.queryFacility(id).then(res => {
        this.formData.facilityNos = res.data.map(item => {
          return item.facilityNo
        })
      })
    },
    save(formData) {
      console.log(this.formData);
      // return
      this.$refs[formData].validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            // 巡检点数组赋值进formData
            let formData = { ...this.formData };
            traceConfigApi.edit(formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.cancel("formData");
                // this.postId = "";
                this.search();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            // 新增接口
            this.formData.organizationNo = sessionStorage.organizationNo;
            let formData = {
              ...this.formData,
              "traceType": "批次",
              "sourceType": "系统生成"
            }
            if (sessionStorage.farmingTypeNo == 'sc') {
              formData = {
                ...formData,
                batchInfo: {
                  batchNo: this.formData.batchNo,
                  fishVarietyName: this.formData.fishVarietyName,
                  fishVarietyId: this.formData.fishVarietyId,
                  breedVarietyPictureNo: this.formData.breedVarietyPictureNo,
                  batchName: this.formData.batchName,
                  organizationNo: sessionStorage.organizationNo,
                  startTime: this.formData.startTime,
                  endTime: this.formData.endTime,
                  facilityNos: this.formData.facilityNos
                }
              }
              if (!this.isClosePond) {
                this.$message.warning('该批次未封塘,请封塘后添加溯源码!')
                return
              }
            }
            console.log('startTime')
            traceConfigApi.add(formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.cancel("formData");
                this.search();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";

::v-deep {
  .el-dialog__wrapper {
    .el-dialog {
      min-width: 30%;
    }
  }
}
</style>
